package org.company.earth.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.log4j.Logger;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class SerializeUtil {

	private static Logger log = Logger.getLogger(SerializeUtil.class);

	/**
	 * 序列化
	 * 
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			log.error("序列化异常", e);
		}
		return null;
	}

	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try {
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			log.error("反序列化异常", e);
		}
		return null;
	}
	
	private Kryo kryo = null;
	
	private SerializeUtil() {
		this.kryo = new Kryo();
	}
	
	private static SerializeUtil instance = null;
	
	public static SerializeUtil getInstance() {
		if(instance == null) {
			instance = new SerializeUtil();
		}
		return instance;
	}
	
	public<T> byte[] serialize(T t,Class<T> clazz) {
		kryo.register(clazz,1);
		ByteArrayOutputStream oos = new ByteArrayOutputStream();
		Output output = new Output(oos);
		kryo.writeObject(output, t);
		return output.getBuffer();
	}
	
	public<T> T unserialize(byte[] bytes,Class<T> clazz) {
		kryo.register(clazz,1);
		kryo.register(clazz);
		Input input = new Input(bytes);
		return kryo.readObject(input, clazz);
	}
}
